package com.ithinks.flow.common.utils;

import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @ClassName CharsetKit
 * @Author MR.LI
 * @date 2020.12.03 18:49
 */
public class CharsetKit {

    //ISO-8859-1
    public static final String ISO_8859_1 = "ISO-8859-1";
    //UTF-8
    public static final String UTF_8 = "UTF-8";
    //gbk
    public static final String GBK = "GBK";

    public static final Charset CHARSET_JSO_8859_1 = Charset.forName(ISO_8859_1);

    /** UTF-8 */
    public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
    /** GBK */
    public static final Charset CHARSET_GBK = Charset.forName(GBK);

    /**
     * 获取字符串编码格式
     * @param charset
     * @return
     */
    public static Charset charset(String charset){
        return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
    }

    /**
     * 将字串符转换成目标格式
     * @param source
     * @param srcCharset
     * @param destCharset
     * @return
     */
    public static String convert(String source ,String srcCharset,String destCharset){
        return convert(source,Charset.forName(srcCharset),Charset.forName(destCharset));
    }

    private static String convert(String source, Charset srcCharset, Charset destCharset) {
        if(null == srcCharset){
            srcCharset = StandardCharsets.ISO_8859_1;
        }
        if(null == destCharset){
            srcCharset = StandardCharsets.UTF_8;
        }
        if(StringUtils.isEmpty(source) || srcCharset.equals(destCharset)){
            return source;
        }
        return new String(source.getBytes(srcCharset),destCharset);
    }

    /**
     * 系统默认编码集
     * @return
     */
    public static String systemCharset(){
        return  Charset.defaultCharset().name();
    }
}
